let house_id = ''
let house_index = 0
Page({
  data: {
    dialogVisible: false,
    houseList: []
  },
  async onShow() {
    this.getHouseList()
  },
  async getHouseList() {
    const res = await wx.http({
      url: '/room',
      method: 'GET',
      // header: {
      //   Authorization: getApp().token
      // }
    })
    if (res.code !== 10000) return wx.utils.toast('获取房屋列表失败')
    this.setData({
      houseList: res.data
    })
  },
  swipeClose(ev) {
    const {
      position,
      instance
    } = ev.detail
    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })

      // 记录要删除房屋的id和索引
      house_id = ev.mark.house_id
      house_index = ev.mark.house_index

      // swiper-cell 滑块关闭
      instance.close()
    }
  },
  dialogClose(e) {
    // 判断用户点击了确认
    e.detail === 'confirm' && this.removeHouse()
  },
  async removeHouse() {
    const {
      code
    } = await wx.http.delete(`/room/${house_id}`)
    if (code !== 10000) return wx.utils.toast('删除失败')
    wx.utils.toast('删除成功')
    // 从房屋数组中删除房屋
    const {
      houseList
    } = this.data
    houseList.splice(house_index, 1)
    this.setData({
      houseList
    })
  },
  goDetail(e) {
    wx.navigateTo({
      url: `/house_pkg/pages/detail/index?id=${e.mark.id}`,
    })
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
})